<?php

namespace StarCloud\Library;

class AES
{
    private $key = "";
    private $method = "aes-256-cbc";

    public function __construct($key)
    {
        $this->key = $key;
    }

    public function encrypt($data)
    {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method)); // 随机生成初始化向量
        $encrypted = openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted . $iv); // 将加密数据和初始化向量进行编码
    }

    public function decrypt($encrypted)
    {
        $decoded = base64_decode($encrypted);
        $iv_length = openssl_cipher_iv_length($this->method);
        $iv = substr($decoded, -$iv_length);
        return openssl_decrypt(substr($decoded, 0, -$iv_length), $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
    }
}